package com.person.jc.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.person.jc.utils.Utils;

/*****************************************************************************
 * @程序名: EllipsisTag.java
 * @日期 : Nov 27, 2012
 * @作者 : 武智雄 (491933243@qq.com)
 * @模块 : [项目]-[一级菜单]-[二级菜单]-[截取字符串变为省略号] 
 * @描述 : [功能简介] 
 * ------------------------------------------------------------ 
 * 修改历史 
 * 序号             日期                      修改人                  修改原因 
 * 1
 * 2
 ******************************************************************************/
public class EllipsisTag extends BodyTagSupport {
	private static final long serialVersionUID = -6187126499239900264L;
	//传入的字符串参数
    private String str;
    //分割之后保留字符串长度
    private int length;
    //省略号位置：1（right）最后，2（center）中间。默认right
    private String location;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            String outString = str;
            if(str != null && length > 0 && str.length() > length + 1){
                if(Utils.isEmpty(location) || "1".equals(location) || "right".equals(location)){
                    outString = outString.substring(0, length) + "...";
                }else if("2".equals(location) || "center".equals(location)){
                    int startLen = 0;
                    int endLen = 0;
                    if(length % 2 == 0){
                        startLen = length / 2;
                        endLen = startLen;
                    }else{
                        startLen = (int)(Math.floor(length/2));
                        endLen = length - startLen;
                    }
                    String startStr = str.substring(0, startLen);
                    String endStr = str.substring(str.length() - endLen);
                    outString = startStr + "..." + endStr;
                }
            }
            out.write(outString);
        }
        catch (Exception e) {
            throw new JspException("Error:" + e.getMessage());
        }
        return EVAL_BODY_INCLUDE;
    }
}
